<template>
    <div class="img-uploader">
        <van-uploader :after-read="afterRead">
            <template>
                <div class="preview-cover van-ellipsis">
                    <img :src="imgUrl" />
                </div>
            </template>
        </van-uploader>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: String
        }
    },
    data() {
        return {
            file: null,
            imgUrl: ""
        };
    },

    watch: {
        value(v) {
            this.getTempFile();
        }
    },

    created() {
        this.getTempFile();
    },

    methods: {
        afterRead(file, detail) {
            let fileData = file.file;
            let fileName = file.file.name;
            console.log("afterRead", fileName, fileData, detail);
            this.$cloud
                .uploadFile({
                    cloudPath: `userAvatar/${fileName}`,
                    filePath: fileData,
                    onUploadProgress: function(progressEvent) {
                        // console.log(progressEvent);
                        // var percentCompleted = Math.round(
                        //     (progressEvent.loaded * 100) / progressEvent.total
                        // );
                    }
                })
                .then(result => {
                    // 上传结果
                    console.log("上传成功", result);
                    this.$emit("input", result.fileID);
                    this.$emit("complete", result);
                })
                .catch(err => {
                    this.$showToast("上传失败");
                });
        },

        getTempFile() {
            this.$cloud
                .getTempFileURL({
                    fileList: [this.value]
                })
                .then(res => {
                    res.fileList.forEach(el => {
                        if (el.code === "SUCCESS") {
                            // console.log(el.tempFileURL);
                            this.imgUrl = el.tempFileURL;
                        } else {
                            //获取下载链接失败
                            this.$showToast("图片加载失败");
                        }
                    });
                });
        }
    }
};
</script>


<style lang="less" scoped>
.img-uploader {
    display: inline-block;
    overflow: hidden;
    height: 100px;
    .body {
        width: 100%;
    }

    .preview-cover {
        position: relative;
        width: 100px;
        height: 100px;
        overflow: hidden;
        background: #eee;
        border-radius: 12px;

        img {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
        }
    }
}
</style>
